package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.annotion.ActionExecOrder;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.workflow.bpmutil.ServiceUtil;
import com.ccp.dev.workflow.model.ProcessCopyTo;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.bpm.BpmRunLog;
import com.ccp.dev.workflow.service.ProcessCopyToService;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.bpm.BpmRunLogService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe: 流程抄送转发 控制器
 *
 * @author :fanruiqi
 * Date: 2019-09-26
 * Since:1
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/processCopyTo")
public class ProcessCopyToController extends SysBaseController {
    private static final Logger logger = LoggerFactory.getLogger(ProcessCopyToService.class);

    @Resource
    private ProcessCopyToService processCopyToService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private BpmRunLogService bpmRunLogService;

    /*-----------------跳转页面--------------------*/

    /**
     * 跳转流程历史管理的抄送转发页面
     * @param request
     * @param model
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "流程历史管理的抄送转发页面跳转" ,
            ownermodel  = SysAuditModelType.PROCESS_MANAGEMENT,
            exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, Model model){
        String runId    = RequestUtil.getString(request,"runId");
        model.addAttribute("runId",runId);
        return getAutoView();
    }

    /**
     * 跳转办结事宜流程的抄送人列表页面
     * @param request
     * @param model
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/getList")
    @Action(description = "办结事宜流程的抄送人列表页面跳转",
            ownermodel  = SysAuditModelType.PROCESS_MANAGEMENT,
            exectype = "页面跳转日志")
    public String viewGetList(HttpServletRequest request, Model model){
        String runId    = RequestUtil.getString(request,"runId");
        model.addAttribute("runId",runId);
        return getAutoView();
    }

    /**
     * 跳转个人办公的抄送转办事宜页面
     * @param request
     * @param model
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/myList")
    @Action(description = "个人办公的抄送转发事宜页面跳转",
            ownermodel  = SysAuditModelType.PROCESS_CENTER,
            exectype = "页面跳转日志")
    public String viewMyList(HttpServletRequest request, Model model){
        return getAutoView();
    }

    /**
     * 跳转我的办结的转发弹窗页面
     * @param request
     * @param model
     * @return 跳转页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX+"/forward")
    @Action(description = "我的办结的转发弹窗页面跳转",
            ownermodel  = SysAuditModelType.PROCESS_CENTER,
            exectype = "页面跳转日志")
    public String viewForward(HttpServletRequest request, Model model) throws Exception{
        String runId    = RequestUtil.getString(request,"runId");
        //获取消息通知类型
        Map handlersMap = ServiceUtil.getHandlerMap();
        int dataPrivacyLevel=1;
        try{
            dataPrivacyLevel = processRunService.getPrivacyLevelByRunId(runId);
        }catch (Exception e){
        }
        model.addAttribute("runId",runId)
            .addAttribute("handlersMap",handlersMap)
            .addAttribute("dataPrivacyLevel",dataPrivacyLevel);
        return getAutoView();
    }

    /*-----------------执行操作--------------------*/

    /**
     * 查询流程历史管理的抄送转发页面列表数据
     * @param request
     * @return 返回数据
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "流程历史管理的抄送转发页面列表数据查询",
            ownermodel  = SysAuditModelType.PROCESS_MANAGEMENT,
            detail      = "查询流程历史管理的抄送转发页面列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData list(HttpServletRequest request){
        try {
            QueryFilter queryFilter = new QueryFilter(request);
            List<ProcessCopyTo> copyToList = processCopyToService.queryList(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success",queryFilter.getPageBean().getTotalCount(),copyToList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 查询个人办公的抄送转办事宜页面列表数据
     * @param request
     * @return 返回数据
     */
    @RequestMapping("/myList")
    @Action(description = "个人办公的抄送转办事宜页面列表数据查询",
            ownermodel  = SysAuditModelType.PROCESS_CENTER,
            detail      = "个人办公的抄送转办事宜页面列表数据查询<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData myList(HttpServletRequest request){
        try {
            QueryFilter queryFilter = new QueryFilter(request);
            queryFilter.put("ccUId", ContextUtil.getCurrentUserId());
            List<ProcessCopyTo> myList = processCopyToService.queryMyList(queryFilter);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("query.success",queryFilter.getPageBean().getTotalCount(),myList);
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 查询流程实例管理的抄送人列表数据
     * @param request
     * @return 返回数据
     */
    @RequestMapping("/getByInstId")
    @Action(description = "流程实例管理的抄送人列表数据查询",
            ownermodel  = SysAuditModelType.PROCESS_MANAGEMENT,
            detail      = "流程实例管理的抄送人列表数据查询成功")
    @ResponseBody
    public ResultData getByInstId(HttpServletRequest request){
        String runId    = RequestUtil.getString(request,"runId");
        List<ProcessCopyTo> copyToList = processCopyToService.queryUserInfoByRunId(runId);
        return getResultDataSuccess("query.success",copyToList);
    }

    /**
     * 标记流程任务抄送消息为已读状态
     * @param request
     * @return 返回结果
     */
    @RequestMapping("/mark")
    @Action(description="标记任务抄送消息为已读",
            ownermodel  = SysAuditModelType.PROCESS_CENTER,
            detail      = "【ContextUtil.getCurrentUser()】将流程<#list RequestUtil.getStringAryByStr(request,\"copyIds\") as item>" +
                    "<#assign copyTo=processCopyToDao.getById(item) />" +
                    "【${copyTo.getSubject()}】<#sep>,</#sep>" +
                    "</#list>任务抄送消息<#if success>成功标记为已读</#if>")
    @ResponseBody
    public ResultData mark(HttpServletRequest request){
        String copyIds  = RequestUtil.getString(request,"copyIds");
        if(StringUtils.isEmpty(copyIds)){
            return getResultDataError("copyTo.null.id.failure");
        }
        try{
            processCopyToService.updateReadStatus(copyIds);
            //2019-11-11    添加系统日志信息
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("copyTo.read.success");
        }catch (Exception e) {
            //2019-11-11    添加系统日志信息
            logger.error(e.getMessage());
            return getResultDataError("copyTo.read.failure");
        }
    }

    /**
     * 删除流程抄送转发的任务消息
     * @param request
     * @return 返回结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @Action(description="删除流程抄送转发任务消息",
            ownermodel  = SysAuditModelType.PROCESS_MANAGEMENT,
            execOrder   = ActionExecOrder.BEFORE,
            detail      = "【ContextUtil.getCurrentUser()】将流程<#list RequestUtil.getStringAryByStr(request,\"copyIds\") as item>" +
                    "<#assign copyTo=processCopyToDao.getById(item) />" +
                    "【${copyTo.getSubject()}】<#sep>,</#sep> " +
                    "</#list>任务抄送消息<#if success>删除成功</#if>")
    @ResponseBody
    public ResultData del(HttpServletRequest request){
        try {
            String[] ids = RequestUtil.getStringAryByStr(request,"copyIds");
            processCopyToService.delByIdArray(ids);
            //2019-11-11    添加日志信息
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("delete.success");
        }catch (Exception e) {
            //2019-11-11    添加日志信息
            logger.error(e.getMessage());
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 我的办结 转发保存弹窗 保存按钮
     * @param request
     * @return 返回结果
     */
    @RequestMapping("/saveForward")
    @Action(description="我的办结的转发弹窗页面保存",
            ownermodel  = SysAuditModelType.PROCESS_CENTER,
            detail      = "流程办结转发<#if success>成功<#elseif failure>失败,不能转发给自己<#elseif failure>失败</#if>")
    @ResponseBody
    public ResultData saveForward(HttpServletRequest request){
        String runId = RequestUtil.getString(request,"runId");
        String users = RequestUtil.getString(request,"users");
        String informType = RequestUtil.getStringAry(request,"informType");
        String suggestion = RequestUtil.getStringAry(request,"suggestion");

        if(StringUtils.isEmpty(runId) || StringUtils.isEmpty(users)){
            return getResultDataError("copyTo.forward.null.failure");
        }else {
            //获取各个人员
            String[] userArr = users.split(",");
            List<String> userList = Arrays.asList(userArr);
            int returnResult = 0;
            try {
                ProcessRun processRun = processRunService.getById(runId);
                SysUser currUser = (SysUser) ContextUtil.getCurrentUser();
                //业务逻辑
                returnResult = processRunService.saveForward(processRun, userList, currUser, informType, suggestion);
                //记录日志
                StringBuffer memo = new StringBuffer("转发了流程：" + processRun.getSubject());
                if (StringUtil.isNotEmpty(suggestion)) {
                    memo.append("，转发意见：" + suggestion);
                }
                bpmRunLogService.addRunLog(runId, BpmRunLog.OPERATOR_TYPE_FINISHDIVERT, memo.toString());
                //2019-11-11    添加系统日志信息
                if (returnResult == 1) {
                    SysAuditThreadLocalHolder.putParamerter("success",true);
                    return getResultDataSuccess("copyTo.forward.save.success");
                } else if (returnResult == -1){
                    SysAuditThreadLocalHolder.putParamerter("failure",true);
                    return getResultDataError("copyTo.forward.save.toMyself.failure");
                }else {
                    SysAuditThreadLocalHolder.putParamerter("failure",false);
                    return getResultDataError("copyTo.forward.save.failure");
                }
            } catch (Exception e) {
                //2019-11-11    添加日志信息
                logger.error(e.getMessage());
                return getResultDataError("copyTo.forward.save.failure");
            }
        }
    }
}
